<template></template>
<script setup>
import { onMounted, onBeforeUnmount } from "vue";
import { zeroTrustLogin, removeScipt } from "@/utils/login.js";
import { useRouter } from "vue-router";
import { ElMessage, ElLoading } from "element-plus";
import store from "@/store";
import { getToken } from "@/utils/auth";
const hasToken = getToken();

let tip = localStorage.getItem("tip");
const router = useRouter();

const handleMessage = async (event) => {
  const { data } = event;
  console.log(event);
  if (typeof data == "string") {
    const loading = ElLoading.service({
      lock: true,
      text: "登录中，请稍后...",
    });
    try {
      const res = await store.dispatch("user/unifiedLogin", { code: data });
      if (res.status > 201) {
        loading.close();
        ElMessage.error("登录失败，请重新扫码");
      } else {
        localStorage.setItem("tip", "");
        tip = "";
        router.push("/");
        loading.close();
      }
    } catch (err) {
      loading.close();
      // ElMessage.error("登录失败，请重新扫码");
    }
  }
};
const userLoing = async () => {
  try {
    const res = await zeroTrustLogin({ id: "unified-login-box", tip });
  } catch (err) {
    ElMessage.error("公共数据共享平台统一登录调用失败，请刷新页面重试！");
  }
};

onMounted(() => {
  userLoing();
  setTimeout(() => {
    window.addEventListener("message", handleMessage);
  }, 2000);
});
onBeforeUnmount(() => {
  removeScipt("unified-login-box");
  window.removeEventListener("message", handleMessage);
});
</script>
<style lang="scss">
#unified-login-box {
  width: 298px;
  height: 298px;
  margin: 0 auto;
  overflow: hidden;
  position: relative;
  iframe {
    position: absolute;
    top: -100px;
    left: -30px;
    border: 1px solid #ddd;
    box-shadow: none;
  }
}
#tipspan {
}
</style>
